package com.manage.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.manage.po.Device;
import com.manage.service.IDeviceService;
import com.manage.util.PagerModel;

@Controller
@Results({
		@Result(name = "device_list", location = "systemAdmin/device/deviceManage.jsp"),
		@Result(name = "device_edit", location = "systemAdmin/device/deviceEdit.jsp"),
		@Result(name = "device_list_lookup", location = "systemAdmin/device/device_list_lookup.jsp"),
		@Result(name = "fileUpload", location = "systemAdmin/device/uploadFile.jsp"), 
	//	@Result(name = "toDownLoad", location = "systemAdmin/device/downLoadFile.jsp"), 
	    @Result(params = {
	                 // 下载的文件格式
	                 "contentType", "application/x-xls",   
	                 "inputName", "inputStream",   
	                 // HTTP协议，使浏览器弹出下载窗口
	                 "contentDisposition", "attachment;filename=\"Microsoft Excel.xls\"",   
	                 // 文件大小
	                 "bufferSize", "10240"},   
	                 name = "download",
	                 // result 类型
	                 type = "stream"),
		@Result(name = "error", location = "error.jsp") })
public class DeviceAction extends BaseAction {

	private static final long serialVersionUID = 6718838822334455667L;
	private final int COLUMN_COUNT = 15;
	@Autowired
	private IDeviceService deviceService;

	private PagerModel pm;
	private int pageNum = 1;
	private int numPerPage = 20;
	private String[] ids; // 删除ID

	private String deviceid;
	// 查找内容
	private String searchDeviceId;
	private String searchDeviceType;
	private String searchAssetNumber;
	private String searchRoomId;

	private String device_id; // 修改id
	private String editorType; // 记录本次的操作类型，是增删改查，以便于这次操作前确定上次操作，防止重复提交

	private Device device;

	// //////////////////////////////////////////////////////////////////////////////
	private File upload;
	// 封装上传文件类型的属性
	private String uploadContentType;
	// 封装上传文件名的属性
	private String uploadFileName;

	
	
	
	@Action("devicemanage")
	public String getDeviceList() {
		pm = deviceService.getDeviceById(deviceid, pageNum, numPerPage);
		return "device_list";
	}

	@Action("SearchDevice_List")
	public String search() {
		// System.out.println(searchDeviceId + "***" + searchAssetNumber + "***"
		// +searchDeviceType + "***" + searchRoomId);
		pm = deviceService.search(searchDeviceId, searchAssetNumber,
				searchDeviceType, searchRoomId, pageNum, numPerPage);
		return "device_list";
	}

	@Action("Device_List_LookUp")
	public String device_list_lookup() {
		pm = deviceService.search(searchDeviceId, searchAssetNumber,
				searchDeviceType, searchRoomId, pageNum, numPerPage);
		return "device_list_lookup";
	}

	// ////////////////////////////////////////////////////////
	@Action("Device_Add")
	public String toAddDeviceInfo() {
		editorType = "add";
		return "device_edit";
	}

	@Action("Device_Modify")
	public String showModify() {
		// System.out.println("---------777777777----------");
		editorType = "modify";
		device = deviceService.getDeviceById(device_id);
		return "device_edit";
	}

	@Action("Device_Save")
	public String save() {
		try {
			if ("add".equals(editorType)) {
				deviceService.save(device);
				return ajaxJsonSuccessMessage("您已经添加成功!", "DEVICEMANAGE",
						"closeCurrent");
			} else {
				deviceService.merge(device);
				return ajaxJsonSuccessMessage("您已经修改成功!", "DEVICEMANAGE",
						"closeCurrent");
			}
		} catch (Exception e) {
			return ajaxJsonWarningMessage("此设备编号已重复！");
		}
	}

	// /////////////////////////////////////////////////////////////
	@Action("Device_BatchDelete")
	public String delete() {
		editorType = "delete";
		deviceService.batchDelete(ids);
		return ajaxJsonSuccessMessage("删除成功", "", "");
	}

	@Action("BatchImport")
	public String batchImport() {

		return "fileUpload";
	}
	
	@Action("prepareDownLoadExcel")
	public String downLoadExcel() throws Exception{		
		// 创建Excel的工作书册 Workbook,对应到一个excel文档
		InputStream is=ServletActionContext.getServletContext().getResourceAsStream("/download/test2003.xls");
		HSSFWorkbook wb = new HSSFWorkbook(is);
		HSSFSheet sheet=wb.getSheetAt(0);
       
		int rowNumber = sheet.getLastRowNum();  // 第一行从0开始算  
        System.out.println("原始数据总行数" + rowNumber + 1);  
        for (int i =1; i <= rowNumber; i++) {  
            Row row = sheet.getRow(i);  
            sheet.removeRow(row);  
        }  
		
		for(int x=0;ids!=null&&x<ids.length; ++x){    //表示遍历行
			try {
					Device device =deviceService.getDeviceById(ids[x]);				

					HSSFRow row=sheet.createRow(x+1);
					if(row==null){
						continue;
					}
					for(int i=0;i<COLUMN_COUNT;++i){
					
						HSSFCell cell=row.createCell(i);
	
						try {
							switch (i) {// 通过列数来判断对应插如的字段
								case 0: cell.setCellValue(device.getDeviceid());break;
								case 1: cell.setCellValue(device.getAssetname());break;
								case 2: cell.setCellValue(device.getAssetnumber());break;
								case 3: cell.setCellValue(device.getDevicetype());break;
								case 4: cell.setCellValue(device.getBuydate().toLocaleString());break;
								case 5: cell.setCellValue(device.getBelongroom( ));break;
								case 6: cell.setCellValue(device.getPrice( ));break;
								case 7: cell.setCellValue(device.getCount( )); break;
								case 8: cell.setCellValue(device.getMeasurunit( ));  break;
								case 9: cell.setCellValue(device.getModel( )); break;
								case 10: cell.setCellValue(device.getManufacturer( )); break;
								case 11: cell.setCellValue(device.getDevstate( )); break;
								case 12: cell.setCellValue(device.getEnterdate().toLocaleString()); break;
								case 13: cell.setCellValue(device.getOperator( )); 	break;
								case 14: cell.setCellValue(device.getNote( )); break;
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						
					}
					
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	
		String filePath = "/download/test2003.xls";
		filePath = ServletActionContext.getServletContext().getRealPath(filePath);
		FileOutputStream os = new FileOutputStream(filePath);
		wb.write(os);
		
		
		is.close();
		os.close();
		sheet=null;
		
		
		
		return "download";
	}
	
//	
//	@Action("PrepareExcel")
//	public String prepareExcel() throws IOException {   
//
//			// 创建Excel的工作书册 Workbook,对应到一个excel文档
//			InputStream is=ServletActionContext.getServletContext().getResourceAsStream("/download/test2003.xls");
//			HSSFWorkbook wb = new HSSFWorkbook(is);
//			HSSFSheet sheet=wb.getSheetAt(0);
//           
//			int rowNumber = sheet.getLastRowNum();  // 第一行从0开始算  
//            System.out.println("原始数据总行数" + rowNumber + 1);  
//            for (int i =1; i <= rowNumber; i++) {  
//                Row row = sheet.getRow(i);  
//                sheet.removeRow(row);  
//            }  
//			
//			for(int x=0;x<ids.length; ++x){    //表示遍历行
//				try {
//						Device device =deviceService.getDeviceById(ids[x]);				
//
//						HSSFRow row=sheet.createRow(x+1);
//						if(row==null){
//							continue;
//						}
//						for(int i=0;i<COLUMN_COUNT;++i){
//						
//							HSSFCell cell=row.createCell(i);
//		
//							try {
//								switch (i) {// 通过列数来判断对应插如的字段
//									case 0: cell.setCellValue(device.getDeviceid());break;
//									case 1: cell.setCellValue(device.getAssetname());break;
//									case 2: cell.setCellValue(device.getAssetnumber());break;
//									case 3: cell.setCellValue(device.getDevicetype());break;
//									case 4: cell.setCellValue(device.getBuydate().toLocaleString());break;
//									case 5: cell.setCellValue(device.getBelongroom( ));break;
//									case 6: cell.setCellValue(device.getPrice( ));break;
//									case 7: cell.setCellValue(device.getCount( )); break;
//									case 8: cell.setCellValue(device.getMeasurunit( ));  break;
//									case 9: cell.setCellValue(device.getModel( )); break;
//									case 10: cell.setCellValue(device.getManufacturer( )); break;
//									case 11: cell.setCellValue(device.getDevstate( )); break;
//									case 12: cell.setCellValue(device.getEnterdate().toLocaleString()); break;
//									case 13: cell.setCellValue(device.getOperator( )); 	break;
//									case 14: cell.setCellValue(device.getNote( )); break;
//								}
//							} catch (Exception e) {
//								e.printStackTrace();
//							}
//							
//						}
//						
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//				
//			}
//		
//			String filePath = "/download/test2003.xls";
//			filePath = ServletActionContext.getServletContext().getRealPath(filePath);
//			FileOutputStream os = new FileOutputStream(filePath);
//			wb.write(os);
//			
//			
//			is.close();
//			os.close();
//			sheet=null;
//			
//        return ajaxJsonSuccessMessage("数据已经导出,请点击获取文件", "", "");   
//	}   
	
    public InputStream getInputStream() {   
		
       // 输出
        try {   
        	String filePath = "/download/test2003.xls";
        	filePath = ServletActionContext.getServletContext().getRealPath(filePath);
        	InputStream in=new FileInputStream(filePath);   
        	//ServletActionContext.getServletContext().getResourceAsStream(filePath);
        	
            return in;   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
        return null;   
    }   


	@Action("UploadFile")
	public String uploadFile() {
		try {
			// 直接在struts.xml文件中配置的属性
			String savePath = "/upload";
			savePath = ServletActionContext.getServletContext().getRealPath(
					savePath);

			// 以服务器的文件保存地址和原文件名建立上传文件输出流
			File target = new File(savePath, uploadFileName);
			if (target.exists()) {
				target.delete();
			}

			FileUtils.copyFile(upload, target);

			loadDeviceInfo(uploadFileName);
		} catch (Exception e) {

			e.printStackTrace();
		}
		return ajaxJsonSuccessMessage("文件上传成功", "", "closeCurrent");
	}

	public void loadDeviceInfo(String uploadFileName) {

		String directory = "/upload";
		String targetDirectory = ServletActionContext.getServletContext()
				.getRealPath(directory);

		File target = new File(targetDirectory, uploadFileName);
		List<Device> deviceList = new ArrayList<Device>();
		try {
			FileInputStream fi = new FileInputStream(target);
			Workbook wb = null;
			// wb = WorkbookFactory.create(fi);
			// if(uploadFileName.endsWith(".xls")) // 2003版本
			// {
			// wb = new HSSFWorkbook(fi);
			// }else{ //2007版本
			// wb = new XSSFWorkbook(fi);
			// }
			if (uploadFileName.matches("^.+\\.(?i)(xls)$")) {// 2003
				wb = new HSSFWorkbook(fi);
			}
			if (uploadFileName.matches("^.+\\.(?i)(xlsx)$")) {// 2007
				wb = new XSSFWorkbook(fi);
			}

			Sheet sheet = wb.getSheetAt(0);

			int rowNum = sheet.getLastRowNum() + 1;
			// 下标从0开始，这里是为了跳过第一行导航栏。
			for (int i = 1; i < rowNum; i++) {
				try {
					Device device = new Device();
					Row row = sheet.getRow(i);
					int cellNum = row.getLastCellNum();
					for (int j = 0; j < cellNum; j++) {
						Cell cell = row.getCell(j);
						String cellValue = null;
						if(cell!=null){
						switch (cell.getCellType()) { // 判断excel单元格内容的格式，并对其进行转换，以便插入数据库
						case 0:
							cellValue = getValueOfNumericCell(cell);
							break;
						case 1:
							cellValue = cell.getStringCellValue();
							break;
						case 2:
							cellValue = String.valueOf(cell.getDateCellValue());
							break;
						case 3:
							cellValue = "";
							break;
						case 4:
							cellValue = String.valueOf(cell
									.getBooleanCellValue());
							break;
						case 5:
							cellValue = String
									.valueOf(cell.getErrorCellValue());
							break;
						}
					}
						
						try {
							switch (j) {// 通过列数来判断对应插如的字段
							case 0:
								device.setDeviceid(cellValue);
								break;
							case 1:
								device.setAssetname(cellValue);
								break;
							case 2:
								device.setAssetnumber(cellValue);
								break;
							case 3:
								device.setDevicetype(cellValue);
								break;
							case 4:
								//TODO
								device.setBuydate(getDateFromString(cellValue));
								break;
							case 5:
								device.setBelongroom(cellValue);
								break;
							case 6:
								device.setPrice(cellValue);
								break;
							case 7:
								device.setCount(cellValue);
								break;
							case 8:
								device.setMeasurunit(cellValue);
								break;
							case 9:
								device.setModel(cellValue);
								break;
							case 10:
								device.setManufacturer(cellValue);
								break;
							case 11:
								device.setDevstate(cellValue);
								break;
							case 12:
								device.setEnterdate(getDateFromString(cellValue));
								break;
							case 13:
								device.setOperator(cellValue);
								break;
							case 14:
								device.setNote(cellValue);
								break;
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					System.out.println(device);
					if (device.getDeviceid() != null
							&& !"".equals(device.getDeviceid().trim())) {
						deviceList.add(device);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			deviceService.save(deviceList);

		} catch (Error e) {
			System.out.println(e);
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	 private static String getValueOfNumericCell(Cell cell) {
		         Boolean isDate = DateUtil.isCellDateFormatted(cell);
		         if (isDate) {
	              return DateFormat.getDateTimeInstance()
		                   .format(cell.getDateCellValue());
		         } else {
		            return String.valueOf((int) cell
							.getNumericCellValue());
	         }
	 }
	 

		// upload的setter和getter方法
		public void setUpload(File upload) {
			this.upload = upload;
		}

		public File getUpload() {
			return (this.upload);
		}

		// uploadContentType的setter和getter方法
		public void setUploadContentType(String uploadContentType) {
			this.uploadContentType = uploadContentType;
		}

		public String getUploadContentType() {
			return (this.uploadContentType);
		}

		// uploadFileName的setter和getter方法
		public void setUploadFileName(String uploadFileName) {
			this.uploadFileName = uploadFileName;
		}

		public String getUploadFileName() {
			return (this.uploadFileName);
		}
 
	public Date getDateFromString(String cellValue){
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date d=null;
		try{
			d=format.parse(cellValue);			
		}catch(Exception e){
			format=new SimpleDateFormat("yyyy-MM-dd");
			try{
				d=format.parse(cellValue);
			}catch(Exception e2){
					
			}
		}
		if(d==null){
			format=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
			try{
				d=format.parse(cellValue);
			}catch(Exception e2){
				format=new SimpleDateFormat("yyyy/MM/dd");
				try{
					d=format.parse(cellValue);
				}catch(Exception e3){
						
				}
			}
		}
		return d;
	}
		
	public IDeviceService getDeviceService() {
		return deviceService;
	}

	public void setDeviceService(IDeviceService deviceService) {
		this.deviceService = deviceService;
	}

	public PagerModel getPm() {
		return pm;
	}

	public void setPm(PagerModel pm) {
		this.pm = pm;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	public String[] getIds() {
		return ids;
	}

	public void setIds(String[] ids) {
		this.ids = ids;
	}

	public String getDeviceid() {
		return deviceid;
	}

	public void setDeviceid(String deviceid) {
		this.deviceid = deviceid;
	}

	public String getSearchDeviceId() {
		return searchDeviceId;
	}

	public void setSearchDeviceId(String searchDeviceId) {
		this.searchDeviceId = searchDeviceId;
	}

	public String getSearchDeviceType() {
		return searchDeviceType;
	}

	public void setSearchDeviceType(String searchDeviceType) {
		this.searchDeviceType = searchDeviceType;
	}

	public String getSearchAssetNumber() {
		return searchAssetNumber;
	}

	public void setSearchAssetNumber(String searchAssetNumber) {
		this.searchAssetNumber = searchAssetNumber;
	}

	public String getSearchRoomId() {
		return searchRoomId;
	}

	public void setSearchRoomId(String searchRoomId) {
		this.searchRoomId = searchRoomId;
	}

	public String getDevice_id() {
		return device_id;
	}

	public void setDevice_id(String device_id) {
		this.device_id = device_id;
	}

	public String getEditorType() {
		return editorType;
	}

	public void setEditorType(String editorType) {
		this.editorType = editorType;
	}

	public Device getDevice() {
		return device;
	}

	public void setDevice(Device device) {
		this.device = device;
	}
}
